/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package crawler.admin.controller;

import crawler.common.CommonUtil;
import crawler.common.PatternData;
import crawler.common.RenderModel;
import crawler.common.UserRole;
import crawler.model.PatternModel;
import crawler.model.PostModel;
import crawler.model.SessionModel;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 *
 * @author ngotandieu
 */
public class AdminPatternController extends HttpServlet {

    private static final Logger logger = Logger.getLogger(AdminPatternController.class);
    private static final DateFormat formatter = new SimpleDateFormat("dd-MM-YYYY HH:mm");
    private static final int POST_PER_PAGE = 10;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handle(req, resp);
    }

    private void handle(HttpServletRequest req, HttpServletResponse resp) {
        try {
            if (!CommonUtil.checkSession(req, resp)) {
                return;
            }
            processs(req, resp);
        } catch (IOException ex) {
            logger.error("AdminPostController.handle:" + ex.getMessage(), ex);
        }
    }

    private void processs(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content;
        String pathInfo = (req.getPathInfo() == null) ? "" : req.getPathInfo();
        switch (pathInfo) {
            case "/edit":
                content = renderDetailPage(req, resp);
                break;
            case "/ajax-edit":
                content = ajaxEdit(req, resp);
                break;
            case "/add":
                content = renderDetailPage(req, resp);
                break;
            case "/ajax-save":
                content = ajaxSave(req, resp);
                break;
            case "/ajax-delete":
                content = ajaxDelete(req, resp);
                break;
            default:
                content = renderIndexPage(req, resp);
        }
        CommonUtil.out(content, resp);
    }

    private String renderIndexPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            if (!CommonUtil.checkAccess(req, UserRole.POST)) {
                resp.sendRedirect("/pattern");
                return "";
            }

//            String pId = req.getParameter("pid") != null ? req.getParameter("pid") : "";
//            if (pId.isEmpty()) {
//                resp.sendRedirect("/post");
//                return "";
//            }

            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "pattern"));
            dic.setVariable("PAGE_TITLE", "Danh sách mẫu tin");

            int page = 1;
            String p = req.getParameter("p") == null ? "1" : req.getParameter("p");
            try {
                page = Integer.parseInt(p);
            } catch (NumberFormatException e) {
            }

            PatternModel patternModel = PatternModel.getInstance();
            List<PatternData> lstPattern = patternModel.getList((page - 1) * POST_PER_PAGE, POST_PER_PAGE);
            if (lstPattern != null) {
                for (PatternData patternData : lstPattern) {
                    TemplateDataDictionary section = dic.addSection("LIST_PATTERN");
                    section.setVariable("ID", String.valueOf(patternData.getId()));
                    section.setVariable("NAME", patternData.getName());
                    section.setVariable("POST_PUBLISHED", patternData.getPublished());
                }
            }
            int count = (int) patternModel.countList();
            String pageNavi = CommonUtil.getPageNavi(page, count, POST_PER_PAGE, "");
            dic.setVariable("PAGENAVI", pageNavi);

            Template template = RenderModel.getAdminCTemplate("pattern_list");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("PatternController.renderIndexPage: " + ex.getMessage(), ex);
        }
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
        return content;
    }

    private String renderDetailPage(HttpServletRequest req, HttpServletResponse resp) {
        String content = "";
        try {
            CommonUtil.prepareHeader(resp, CommonUtil.HEADER_HTML);
            
            boolean exists = false;
            PatternData patternData = null;
            
            TemplateDataDictionary dic = TemplateDictionary.create();
            dic.setVariable("HEADER", CommonUtil.getAdminHeader());
            dic.setVariable("FOOTER", CommonUtil.getAdminFooter());
            dic.setVariable("MENU", CommonUtil.getAdminMenu(req));
            dic.setVariable("SIDEBAR", CommonUtil.getAdminSidebar(req, "pattern"));
            dic.setVariable("PAGE_TITLE", "Thêm mới mẫu tin tức");
            dic.showSection("ADD_PAGE");
            dic.showSection("ACTIVE_YES");

            String pId = req.getParameter("id");
            if(pId != null && !pId.isEmpty()){
                PatternModel patternModel = PatternModel.getInstance();
                patternData = patternModel.getById(pId);
            }
            if(patternData!=null){
                exists = true;
                dic.setVariable("PATTERN_ID", pId);
                dic.setVariable("PATTERN_NAME", patternData.getName());
                dic.setVariable("LINK", patternData.getLink());
                dic.setVariable("TITLE", patternData.getTitle());
                dic.setVariable("CATEGORY", patternData.getCategory());
                dic.setVariable("THUMB", patternData.getThumb());
                dic.setVariable("DESC", patternData.getDesc());
                dic.setVariable("CONTENT", patternData.getContent());
                dic.setVariable("JOURNALIST", patternData.getJournalist());
                dic.setVariable("TAGS", patternData.getTags());
                dic.setVariable("PUBLISHED", patternData.getPublished());
                dic.setVariable("AUTHOR", patternData.getName());
                dic.setVariable("PAGE_TITLE", "Cập nhật mẫu tin tức");
            }

            Template template = RenderModel.getAdminCTemplate("pattern_add");
            content = template.renderToString(dic);
        } catch (Exception ex) {
            logger.error("AdminPostController.renderAddPage: " + ex.getMessage(), ex);
        }
        return content;
    }

    private String ajaxSave(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);

        String content;
        int error = 0;
        String msg = "Lưu Pattern thành công.";
        Map<String, String> data = new HashMap<>();
        try {
            String patternId = req.getParameter("patternId"),
                patternName = req.getParameter("pName"),
                link = req.getParameter("link"),
                title = req.getParameter("title"),
                category = req.getParameter("category"),
                desc = req.getParameter("desc"),
                pcontent = req.getParameter("content"),
                thumb = req.getParameter("thumb"),
                published = req.getParameter("published"),
                tags = req.getParameter("tags"),
                journalist = req.getParameter("journalist");

            if (patternId!=null && patternId.isEmpty()) {
                error = -1;
                msg = "Pattern ID không được trống.";
            } else {
                PatternModel postModel = PatternModel.getInstance();
                SessionModel sessionModel = SessionModel.getInstance();
                String userLogin = sessionModel.getUserLogin(req);

                long ptime = System.currentTimeMillis();

                PatternData patternData =
                        new PatternData(patternId, patternName, link, title, category,
                                thumb, desc, pcontent, tags, journalist,
                                published, userLogin, ptime, userLogin, ptime);
                if("0".equals(patternId)){
                    patternId = postModel.add(patternData);
                }else{
                    postModel.update(patternData);
                }
                data.put("id", patternId);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    private String ajaxEdit(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);
        if (!CommonUtil.checkAccess(req, UserRole.POST_EDIT)) {
            return CommonUtil.toPermissionDenied();
        }

        String content;
        int error = 0;
        String msg = "Cập nhật tin tức thành công.";
        Map<String, String> data = new HashMap<>();
        try {
//            String pId = req.getParameter("pid") != null ? req.getParameter("pid") : "";
//            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
//            String title = req.getParameter("title") != null ? req.getParameter("title") : "";
//            String desc = req.getParameter("desc") != null ? req.getParameter("desc") : "";
//            String scontent = req.getParameter("content") != null ? req.getParameter("content") : "";
//            String status = req.getParameter("status") != null ? req.getParameter("status") : "0";
//            String time = req.getParameter("time") != null ? req.getParameter("time") : "0";
//            String slug = CommonUtil.URLFriendly(title);
//
//            if (pId.isEmpty() || id.isEmpty()) {
//                error = -1;
//                msg = "pid không được trống.";
//            } else {
//                PostModel postModel = PostModel.getInstance();
//                SessionModel sessionModel = SessionModel.getInstance();
//                String userLogin = sessionModel.getUserLogin(req);
//
//                long ptime = System.currentTimeMillis();
//                if (!time.isEmpty()) {
//                    Date date = formatter.parse(time);
//                    ptime = date.getTime();
//                }
//
//                PostData postData = new PostData(pId, id, title, slug, desc, scontent, userLogin, Short.parseShort(status), ptime);
//                boolean updatePost = postModel.updatePost(postData);
//                if (!updatePost) {
//                    error = -1;
//                    msg = "Có lỗi xảy ra.";
//                }
//            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg, data);
        return content;
    }

    private String ajaxDelete(HttpServletRequest req, HttpServletResponse resp) {
        CommonUtil.prepareHeader(resp, CommonUtil.HEADER_JS);

        String content;
        int error = 0;
        String msg = "Xoá Post thành công.";
        try {
            String id = req.getParameter("id") != null ? req.getParameter("id") : "";
            if (id.isEmpty()) {
                msg = "Post Id không được trống.";
                error = -1;
            } else {
                PatternModel patternModel = PatternModel.getInstance();
                boolean success = patternModel.delete(id);
                if (!success) {
                    msg = "Có lỗi xảy ra.";
                    error = -1;
                }
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msg = ex.getMessage();
            error = -1;
        }
        content = CommonUtil.toJSON(error, msg);
        return content;
    }
}
